package com.gome.axwl.aoc.common.util;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.S3Object;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

@Component
public class XskyS3Util {

    private final static Logger log = LoggerFactory.getLogger(XskyS3Util.class);

    private static String bucketName;
    private static String akey;
    private static String skey;
    private static String endpoint;

    @Value("${ceph.bucketName}")
    public void setBucketName(String bucketName1) {
        bucketName = bucketName1;
    }

    @Value("${ceph.akey}")
    public void setAkey(String akey1) {
        akey = akey1;
    }

    @Value("${ceph.skey}")
    public void setSkey(String skey1) {
        skey = skey1;
    }

    @Value("${ceph.endpoint}")
    public void setEndpoint(String endpoint1) {
        endpoint = endpoint1;
    }

    /**
     * 上传文件到对象服务器
     *
     * @param file
     * @return
     */
    public static String uploadAndReturnUrl(MultipartFile multipartFile, File file, String fileName) {
        try {
            if (!XskyS3Basic.init_s3_lib(endpoint, akey, skey)) {
                log.error("上传文件失败，文件名称：{}", fileName);
                return "";
            }
            if (!XskyS3Basic.HasBucket(bucketName)) {
                XskyS3Basic.CreatingBucket(bucketName);
                log.info("Successful create bucket: " + bucketName + "\n");
            } else {
                log.info("Bucket " + bucketName + " is exists!\n");
            }
            File newFile = File.createTempFile("tmp", null);
            if(file == null){
                multipartFile.transferTo(newFile);
            }else{
                newFile = file;
            }
            XskyS3Basic.WritingAnObject(bucketName, fileName, newFile);
            XskyS3Basic.setFileAuth(bucketName, fileName, CannedAccessControlList.PublicReadWrite);
            newFile.delete();           //删除文件
            log.info("Successful put object: " + fileName + "\n");
            return XskyS3Basic.getDownLoadUrl(bucketName, fileName);

        } catch (AmazonServiceException ase) {
            log.error("Caught an AmazonServiceException, which" + " means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            log.error("Error Message:    " + ase.getMessage());
            log.error("HTTP Status Code: " + ase.getStatusCode());
            log.error("AWS Error Code:   " + ase.getErrorCode());
            log.error("Error Type:       " + ase.getErrorType());
            log.error("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            log.error("Caught an AmazonClientException, which means" + " the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            log.error("Error Message: " + ace.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 删除文件
     * @param fileName
     */
    public static void deleteFile(String fileName) {
        try {
            // Init s3 lib
            if (!XskyS3Basic.init_s3_lib(endpoint, akey, skey)) {
                log.error("init s3 lib failed!\n");
                return;
            }
            // Delete Object
            XskyS3Basic.DeletingAnObject(bucketName, fileName);
        } catch (AmazonServiceException ase) {
            log.error("Caught an AmazonServiceException, which" + " means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            log.error("Error Message:    " + ase.getMessage());
            log.error("HTTP Status Code: " + ase.getStatusCode());
            log.error("AWS Error Code:   " + ase.getErrorCode());
            log.error("Error Type:       " + ase.getErrorType());
            log.error("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            log.error("Caught an AmazonClientException, which means" + " the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            log.error("Error Message: " + ace.getMessage());
        }
    }

    /**
     * 生成一个txt
     * @param fileName
     * @param input
     */
    public static void createTxt(String fileName, ByteArrayInputStream input) {
        try {
            // Init s3 lib
            if (!XskyS3Basic.init_s3_lib(endpoint, akey, skey)) {
                log.error("init s3 lib failed!\n");
                return;
            }
            // create Object
            XskyS3Basic.createTxt(bucketName, fileName, input);
        } catch (AmazonServiceException ase) {
            log.error("Caught an AmazonServiceException, which" + " means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            log.error("Error Message:    " + ase.getMessage());
            log.error("HTTP Status Code: " + ase.getStatusCode());
            log.error("AWS Error Code:   " + ase.getErrorCode());
            log.error("Error Type:       " + ase.getErrorType());
            log.error("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            log.error("Caught an AmazonClientException, which means" + " the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            log.error("Error Message: " + ace.getMessage());
        }
    }

    /**
     * 根据文件名读取TXT内容
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String readFile(String fileName) throws IOException {
        if (!XskyS3Basic.init_s3_lib(endpoint, akey, skey)) {
            log.error("init s3 lib failed!\n");
            return "";
        }
        S3Object s3object = XskyS3Basic.ReadingAnObject(bucketName, fileName);
        return displayTextInputStream(s3object.getObjectContent());
    }

    private static String displayTextInputStream(InputStream input) throws IOException {
        // Read one text line at a time and display.
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String content = "";
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            content = content + line;
        }
        return content;
    }

}
